#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
// #include<stdio.h>
// #include<math.h>
#include <pthread.h>

#include "Log.hpp"

using std::cin;
using std::cout;
using std::endl;

#define BACK_LOG 5
// 编写该部分的思路为：先初始化，初始化包括：创立套接字，绑定端口号，设立监听状态
// 然后是单例模式的设计要求：新增一个静态成员与获取静态成员的函数，要注意多线程下的创建多个对象的问题，所以要使用锁
// 后期保证调试方便，需要新增日志部分
class Tcpserver
{
public:

    static Tcpserver* Getinstance(int port )
    {
        static pthread_mutex_t lock =PTHREAD_MUTEX_INITIALIZER;
        if(svr == nullptr)
        {
            pthread_mutex_lock(&lock);
            if(svr == nullptr)
            {
                svr = new Tcpserver(port);
                svr->Init();
            }
                pthread_mutex_unlock(&lock);
        }
        return svr;
    }

    void Init()
    {
        Socket();
        Bind();
        Listen();
        LOG(INFO,"Init success");
    }
    
    void Socket()
    {
        listen_sock_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_sock_ < 0)
        {
            // 后期用日志替换
            LOG(FATAL,"Create Socket failed");
            exit(1);
        }
        // 下面是为了解决地址复用的问题，之所以存在地址复用
        // 是因为在TCP协议当中，主动断开链接的一方会进入time_out状态，等待网络当中的历史报文自动消散
        int opt = 1;
        setsockopt(listen_sock_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        LOG(INFO,"Create Socket Success");
    }

    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(listen_sock_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL,"Bind Socket failed");
            exit(2);
        }
        LOG(INFO,"Bind Socket Success");
    }
    void Listen()
    {
        if (listen(listen_sock_, BACK_LOG) < 0)
        {
            
            LOG(FATAL,"Listen Socket failed");
            exit(3);
        }
        LOG(INFO, "Listen Socket Success" );
    }

    ~Tcpserver()
    {
        if (listen_sock_ >= 0)
            close(listen_sock_);
    }

    int Sock()
    {
        return listen_sock_;
    }

private:
    // 将该Tcp套接字设计为单例模式，防止外部的拷贝
    Tcpserver(int port )
        : port_(port), listen_sock_(-1)
    {
    }
    Tcpserver(const Tcpserver &tcp) = delete;

private:
    int port_;
    int listen_sock_;
    static Tcpserver *svr;
};

Tcpserver *Tcpserver::svr = nullptr;
